import { defineStore } from 'pinia';

import { loginApi, logoutApi } from '@/api/auth';
import { getUserInfo, updateUserProfile } from '@/api/identity/user';
import { resetRouter } from '@/router';
import { store } from '@/store';

import { LoginData } from '@/api/identity/auth/types';
import { UserInfo, UserProfileReponse, UserForm } from '@/api/identity/user/types';

import { useStorage } from '@vueuse/core';

export const useUserStore = defineStore('user', () => {
  // state
  const token = useStorage('accessToken', '');
  const userName = ref('');
  const email = ref('');
  const name = ref('');
  const surname = ref('');
  const phoneNumber = ref('');
  const extraProperties = ref(null)
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const avatar = ref<any>()
  const introduction = ref('');
  // const perms = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限

  /**
   * 登录调用
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    loginData.client_id = "CMS_App";
    loginData.grant_type = "vertifycode";
    loginData.scope = "CMS";
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then(response => {
         // console.log('loginApi', response)
          const { token_type, access_token } = response;
          token.value = token_type + ' ' + access_token; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          resolve();
        })
        .catch(error => {
          reject(error);
          debugger
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getUserInfo()
        .then(( data ) => {

       
          if (!data) {
            return reject('Verification failed, please Login again.');
          }
          // console.log('userinfo',data)
          userName.value = data.userName;
          email.value = data.email;
          phoneNumber.value=data.phoneNumber;
          name.value = data.name;
          surname.value = data.surname;
          avatar.value = data.extraProperties.Avatar;
          introduction.value=data.extraProperties.Introduction;
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  function setUserInfo(userInfo: UserForm) {
    return new Promise<UserProfileReponse>((resolve, reject) => {
      updateUserProfile(userInfo).then(
        ( data:any ) => {
          // console.log(data)
          // debugger;
          userName.value = data.userName;
          email.value=data.email;
          name.value=data.name;
          surname.value=data.surname;
          phoneNumber.value=data.phoneNumber;
          avatar.value=data.extraProperties.Avatar;
          introduction.value=data.extraProperties.Introduction;
       
          resolve(data as UserProfileReponse);
        }
      ).catch(error => {
        reject(error);
      });

    });
  }

  function setRoles(roles: any) {
     roles.value=roles;
  }

  // 注销
  function logout() {
    return new Promise<void>((resolve, reject) => {

      resetRouter();
      resetToken();
      // logoutApi()
      //   .then(() => {

      //     resolve();
      //   })
      //   .catch(error => {
      //     reject(error);
      //   });
    });
  }

  // 重置
  function resetToken() {
    token.value = '';
    userName.value = '';
    email.value = '';
    name.value = "";
    surname.value = '';
    phoneNumber.value = '';
    extraProperties.value = null;
    roles.value = [];
    avatar.value = null;
    introduction.value = "";


  }
  return {
    token,
    userName,
    email,
    name,
    surname,
    phoneNumber,
    extraProperties,
    roles,
    avatar,
    introduction,
    login,
    getInfo,
    setUserInfo,
    logout,
    resetToken,
    setRoles
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
